package com.cscec5b.inspection.controller;

import com.cscec5b.inspection.config.AppProperties;
import com.cscec5b.inspection.config.RateLimiterService;
import com.cscec5b.inspection.dto.ProjectSyncDtos.*;
import com.cscec5b.inspection.service.ProjectSyncService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/projects")
public class ProjectSyncController {

    private final ProjectSyncService service;
    private final RateLimiterService limiter;
    private final AppProperties props;

    public ProjectSyncController(ProjectSyncService service, RateLimiterService limiter, AppProperties props) {
        this.service = service; this.limiter = limiter; this.props = props;
    }

    @PostMapping(value = "/sync", consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ProjectSyncResponse sync(@RequestBody @Valid ProjectSyncRequest req, HttpServletRequest http) {
        if (req.data.size() > props.getBatchLimit()) {
            throw new IllegalArgumentException("batch too large");
        }
        String clientId = (String) http.getAttribute("clientId");
        if (!limiter.tryConsume(clientId)) throw new TooManyRequestsException();
        String requestId = http.getHeader("X-Request-Id");
        long ts = Long.parseLong(http.getHeader("X-Timestamp"));
        return service.processSync(clientId, requestId, ts, req);
    }

    @ResponseStatus(code=org.springframework.http.HttpStatus.TOO_MANY_REQUESTS)
    static class TooManyRequestsException extends RuntimeException {}
}
